package gamePlay;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.StreamTokenizer;

public class PBMLoader {

	public int[][] read(String file) {

		int[][] data2D = null; // raw picdata as 2dim array

		int X; // The width of the picture.
		int Y; // The height of the picture.
		int Colors; // number of colors (usually 256)

		try {
			FileInputStream fis = new FileInputStream(file);
			BufferedReader r = new BufferedReader(new InputStreamReader(fis));
			StreamTokenizer st = new StreamTokenizer(r);
			int type;
			st.commentChar('#');
			st.eolIsSignificant(false);
			st.slashStarComments(false);
			st.slashSlashComments(false);
			try {
				type = st.nextToken();
				if (type == st.TT_NUMBER || st.sval.compareTo("P5") != 0) {
					System.err
							.println("ERROR: " + file + " is not a PGM-file!");
				}

				type = st.nextToken();
				X = (int) st.nval; // width
				type = st.nextToken();
				Y = (int) st.nval; // height
				type = st.nextToken();
				Colors = (int) st.nval + 1; // max. color value +1

				data2D = new int[X][Y];
				for (int row = 0; row < Y; row++)
					for (int col = 0; col < X; col++)
						data2D[col][row] = (r.read());

			} catch (IOException e) {
				System.err.println("Error while reading file " + file);
			}

		} catch (FileNotFoundException e) {
			System.err.println("Error: File " + file + " not found!");
		}

		return data2D;

	}
}
